using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.IO;
using TVT.Common.Helpers;
using Common.Context;

namespace TVT.Common.Exceptions
{
    public class ExceptionLogger
    {
        private static bool logExceptions = Convert.ToBoolean(Context.GetInstance().GetValueFromContext(WellKnownKeys.LogExceptionsKey));

        private ExceptionLogger()
        {

        }


        public static void HandleException(Exception ex)
        {
            if (!logExceptions) return;

            string strData = String.Empty;

            Guid eventId = System.Guid.NewGuid();
                
            string file = Context.GetInstance().GetValueFromContext(WellKnownKeys.ExceptionLogDataAccessFileKey);

            string referer = String.Empty;

            string logDateTime = DateTime.Now.ToString();

            strData = "\nSOURCE: " + ex.Source +

            "\nLogDateTime: " + logDateTime +

            "\nMESSAGE: " + ex.Message +

            "\nTARGETSITE: " + ex.TargetSite +

            "\nSTACKTRACE: " + ex.StackTrace;

            StreamWriter writer;

            if (File.Exists(file))
            {
                writer = File.AppendText(file);
            }
            else
            {
                writer = new StreamWriter(file);
            }

            writer.AutoFlush = true;
            writer.Write(strData);
            writer.Close();
        }
    }
}